package vip.redme.memory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.redme.memory.exception.BizException;
import vip.redme.memory.pojo.dto.UserDto;
import vip.redme.memory.pojo.entity.User;
import vip.redme.memory.repository.UserRepository;
import vip.redme.memory.response.BaseResultCode;
import vip.redme.memory.service.AuthService;
import vip.redme.memory.util.Args;

import javax.transaction.Transactional;

/**
 * AuthServiceImpl
 *
 * @author HUZHAOYANG
 * @version 1.0
 * @date 2021/9/5 13:38
 */
@Slf4j
@Transactional
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDto login(User user) {

        User userInDB = userRepository.findByUserNameAndPassword(user.getUserName(), user.getPassword());
        if (Args.isEmpty(userInDB)) {
            throw BizException.of(BaseResultCode.RECORD_NOT_EXIST);
        }
        return BeanUtil.toBean(userInDB, UserDto.class);
    }

    @Override
    public UserDto loginByToken(String token) {
        User userInDB = userRepository.findByToken(token);
        if (Args.isEmpty(userInDB)) {
            throw BizException.of(BaseResultCode.RECORD_NOT_EXIST);
        }
        return BeanUtil.toBean(userInDB, UserDto.class);
    }

    @Override
    public UserDto register(User user) {
        user.setToken(UUID.fastUUID().toString(true));
        userRepository.save(user);
        return BeanUtil.toBean(user, UserDto.class);
    }
}
